from django.db import models

from library.middle_control.base_model import BaseModel
from django.contrib.auth.models import User


class Book(BaseModel):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    isbn = models.CharField(max_length=13, unique=True, verbose_name='图书编号')
    published_date = models.DateField()
    available = models.BooleanField(default=True)

    class Meta:
        db_table = 'book'

    def to_json(self):
        return {
            'id': self.id,
            'title': self.title,
            'author': self.author,
            'isbn': self.isbn,
            'published_date': self.published_date,
            'available': self.available
        }


class Borrowing(BaseModel):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    borrow_date = models.DateField(auto_now_add=True)
    due_date = models.DateField()
    returned = models.BooleanField(default=False, verbose_name='还书状态')

    class Meta:
        db_table = 'borrowing'

    def to_json(self):
        return {
            'id': self.id,
            'book': self.book,
            'user': self.user,
            'borrow_date': self.borrow_date,
            'due_date': self.due_date,
            'returned': self.returned
        }
